package 数组题目.数组变换;

//螺旋遍历矩阵2
//https://leetcode.cn/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/description/
class 螺旋遍历矩阵2 {
    public int[] spiralArray(int[][] array) {
        if (array == null || array.length == 0 || array[0].length == 0) {
            return new int[0];
        }
        int m = array.length, n = array[0].length;
        int[] ans = new int[m * n];
        int nums = 0;
        int top = 0;
        int bottom = array.length - 1;
        int left = 0;
        int right = array[0].length - 1;
        while (nums < m * n) {
            // 从左到右
            if (top <= bottom) {
                for (int i = left; i <= right; i++) {
                    ans[nums++] = array[top][i];
                }
                top++;
            }
            // 从上到下
            if (right >= left) {
                for (int i = top; i <= bottom; i++) {
                    ans[nums++] = array[i][right];
                }
                right--;
            }
            // 从右到左
            if (bottom >= top) {
                for (int i = right; i >= left; i--) {
                    ans[nums++] = array[bottom][i];
                }
                bottom--;
            }
            // 从下到上
            if (right >= left) {
                for (int i = bottom; i >= top; i--) {
                    ans[nums++] = array[i][left];
                }
                left++;
            }
        }
        return ans;
    }
}
